import { createStore } from 'vuex'
import { getUserInfo, getUserPermissions } from '../utils/api'

const store = createStore({
  state: {
    token: localStorage.getItem('token') || '',
    userInfo: JSON.parse(localStorage.getItem('userInfo') || '{}'),
    permissions: []
  },
  mutations: {
    SET_TOKEN(state, token) {
      state.token = token
      localStorage.setItem('token', token)
    },
    SET_USER_INFO(state, userInfo) {
      state.userInfo = userInfo
      localStorage.setItem('userInfo', JSON.stringify(userInfo))
    },
    SET_PERMISSIONS(state, permissions) {
      state.permissions = permissions
    },
    CLEAR_USER(state) {
      state.token = ''
      state.userInfo = {}
      state.permissions = []
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
    }
  },
  actions: {
    // 获取用户信息
    async getUserInfo({ commit }) {
      try {
        const response = await getUserInfo()
        const userInfo = response.data.data
        commit('SET_USER_INFO', userInfo)
        return userInfo
      } catch (error) {
        console.error('获取用户信息失败', error)
        return null
      }
    },
    // 获取用户权限
    async getUserPermissions({ commit }) {
      try {
        const response = await getUserPermissions()
        const permissions = response.data.data
        commit('SET_PERMISSIONS', permissions)
        return permissions
      } catch (error) {
        console.error('获取用户权限失败', error)
        return []
      }
    },
    // 登出
    logout({ commit }) {
      commit('CLEAR_USER')
    }
  },
  getters: {
    isAuthenticated: state => !!state.token,
    userInfo: state => state.userInfo,
    hasPermission: state => permission => {
      if (!permission) return true
      return state.permissions.includes(permission)
    },
    hasAnyPermission: state => permissions => {
      if (!permissions || permissions.length === 0) return true
      return permissions.some(permission => state.permissions.includes(permission))
    },
    hasAllPermissions: state => permissions => {
      if (!permissions || permissions.length === 0) return true
      return permissions.every(permission => state.permissions.includes(permission))
    }
  }
})

export default store